<template>
  <div>
    <UserSelect
      ref="userSelect"
      :initialValue="initialValue"
      @e-userData="handleAdd"
    />
  </div>
</template>
<script>
import Bus from '@/utils/bus.js'
export default {
  components: {
    UserSelect: () => import('@/components/userSelect'),
  },
  data() {
    return {
      title: '新增',
      initialValue: {
        userId: [],
      },
    }
  },
  mounted() {
    this.$bus.$on('showDialogEduClassesStudentAdd', this.init)
  },
  beforeDestroy() {
    this.$bus.$off('showDialogEduClassesStudentAdd')
  },
  methods: {
    async init() {
      let { classesId } = this.$route.query
      let obj = {
        page: 1,
        limit: 999,
        classesId,
      }
      let res = await this.$store.dispatch('queryEduClassesStudent', obj)
      this.initialValue.userId = res.data.map((v) => v.studentId)
      Bus.$emit('userSelect')
    },
    handleAdd(v) {
      if (!v.userId.length) return
      let { userId } = v
      let arr = []
      let { classesId } = this.$route.query
      userId.forEach((item) => {
        let obj = {
          classesId,
          studentId: item.id,
          studentName: item.userName,
        }
        arr.push(obj)
      })
      this.submitForm(arr)
    },
    async submitForm(arr) {
      let dispatchType =
        this.title == '新增'
          ? 'addBatchEduClassesStudent'
          : 'updateEduClassesStudent'
      await this.$store.dispatch(dispatchType, arr)
      this.done()
    },
    done() {
      this.$bus.$emit('refreshEduClassesStudentList')
      this.$message({
        message: '操作成功',
        type: 'success',
      })
    },
    resetForm(form) {
      this.$refs[form].resetFields()
    },
  },
}
</script>